
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#include <jni.h>
#include <stdio.h>
#include "util/errorMesg.hpp"

//JVM 环境
JavaVM *jvm;           
JNIEnv *env;         

void creatJvm()
{
    char *java_home;
    const char *jvmPath = "/bin/server/jvm";
    if (!(java_home = getenv("JAVA_HOME")))
    {
        errorMessageBox("未找到JVM环境，JAVA_HOME");
        return;
    }
     // 显式加载 jvm.dll
    HINSTANCE hinst = LoadLibraryA(jvmPath);

      // 获取 JNI_CreateJavaVM 函数的地址
    FARPROC createJavaVM = GetProcAddress(hinst, "JNI_CreateJavaVM");
    if (createJavaVM == NULL) {
        std::cerr << "Failed to get JNI_CreateJavaVM function" << std::endl;
        errorMessageBox("Failed to get JNI_CreateJavaVM function");
        return;
    }

    if (hinst == NULL) {
        std::cerr << "Failed to load jvm.dll" << std::endl;
        errorMessageBox("Failed to load jvm.dll");
        return ;
    }

    JavaVMInitArgs vm_args; /* JDK/JRE 19 VM initialization arguments */

    int optionSize=1;
    JavaVMOption *options = new JavaVMOption[optionSize];

    options[0].optionString = "-Djava.class.path=D:/test/cjava/build/libs/cjava-1.0-SNAPSHOT.jar";
    vm_args.version = JNI_VERSION_10;
    vm_args.nOptions = optionSize;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = JNI_TRUE;
    std::cout << "JNI_CreateJavaVM" << std::endl;

    typedef jint (JNICALL * JNI_CreateJavaVM_Type)(JavaVM**, void**, void*);

    // 调用 JNI_CreateJavaVM 函数
    jint result = reinterpret_cast<JNI_CreateJavaVM_Type>(createJavaVM)(&jvm, (void **)&env, &vm_args);
    if (result != JNI_OK) {
        std::cerr << "Failed to create Java VM" << std::endl;
        errorMessageBox("Failed to create Java VM");
        return ;
    }


}